import json
import random
import subprocess
import re
import time
import sys

from utils import sendmail, dayUtils


# 获取脚本参数
def get_script_param():
    return sys.argv


def get_sleep_time(min, max):
    s = random.randint(min, max)
    print("休眠{}秒".format(s))
    return s


# 获取curl命令
def get_command():
    with open('settings.json') as setting:
        s = json.load(setting)
    return s["command"]


# 获取邮件的账号密码
def get_acc_settings():
    with open('settings.json') as setting:
        acc = json.load(setting)
    return acc["user_name"], acc["password"]


if __name__ == '__main__':
    # 获取curl命令
    command = get_command()

    param_list = get_script_param()
    if '-i' in param_list:
        # -i 代表立即执行，不休眠
        pass
    else:
        # 休眠随机时间
        time.sleep(get_sleep_time(100, 1000))

    exitcode, output = subprocess.getstatusoutput(command)
    # 退出码
    # print(exitcode)
    # 输出
    print(output)

    # 匹配签到结果err_code
    obj_err_code = re.compile(r'"error_code":(?P<error_code>\d+),', re.S)
    # 匹配签到结果checkin_num 字符双引号可有可无("?)
    obj_checkin_num = re.compile(r'"checkin_num":("?)(?P<checkin_num>\d+)("?),', re.S)
    # 匹配签到结果err_msg
    obj_err_msg = re.compile(r'"error_msg":"(?P<error_msg>.*?)",', re.S)

    # 获取err_code
    err_code = obj_err_code.search(output).group('error_code')

    receiver = ['675696416@qq.com']
    user_name, password = get_acc_settings()
    subject = dayUtils.get_today('-') + '什么值得买签到结果'
    try:
        if str(err_code) != '0':
            error_msg = obj_err_code.search(output).group('error_msg')
            msg = "签到失败，error_code : %s , err_msg : %s" % (str(err_code), error_msg)
            subject = "【签到失败】" + subject
            print(msg)
        else:
            checkin_num = int(obj_checkin_num.search(output).group('checkin_num'))
            msg = "签到成功，连续签到天数：%d" % checkin_num
            subject = "【签到成功】" + subject
            print(msg)

        # 发送邮件
        sendmail.send_mail(user_name=user_name, password=password, subject=subject, receiver=receiver, msg=msg)
    except Exception as e:
        except_msg = """签到程序出错！！错误原因：{}。<br>""".format(repr(e)) \
                     + """\n""" \
                     + """请求error code：{} """.format(err_code)
        print(except_msg)
        sendmail.send_mail(user_name=user_name, password=password, subject=subject, receiver=receiver, msg=except_msg)
